/*
 *RadioAppGenericException.java
 *
 * Copyright(c) IronOne Technologies (Pvt) Ltd.  All Rights Reserved.
 * This software is the proprietary information of IronOne Technologies (Pvt) Ltd.
 *
 */
package com.ironone.streaming.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;

/**
 * {This class Handles application error state }
 *
 * @Created on July 02, 2014 : 4:07:00 PM
 * @author Suren Manawatta
 */
public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
	private final Activity context;
	private final String LINE_SEPARATOR = "\n";

	public ExceptionHandler(Activity act) {
		context = act;
	}

	@SuppressWarnings("deprecation")
	public void uncaughtException(Thread thread, Throwable exception) {
			StringWriter stackTrace = new StringWriter();
			exception.printStackTrace(new PrintWriter(stackTrace));
			StringBuilder errorReport = new StringBuilder();
			errorReport.append("************ CAUSE OF ERROR ************\n\n");
			
			errorReport.append("Exception:\n");
			errorReport.append(exception.getMessage() + "\n\n");
			
			errorReport.append("Inner Exception:\n");
			errorReport.append(exception.getCause().getMessage() + "\n\n");
			
			errorReport.append("StackTrace:" + "\n");
			errorReport.append(stackTrace.toString() + "\n");

			errorReport.append("\n************ DEVICE INFORMATION ***********\n");
			errorReport.append("Brand: ");
			errorReport.append(Build.BRAND);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Device: ");
			errorReport.append(Build.DEVICE);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Model: ");
			errorReport.append(Build.MODEL);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Id: ");
			errorReport.append(Build.ID);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Product: ");
			errorReport.append(Build.PRODUCT);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("\n************ FIRMWARE ************\n");
			errorReport.append("SDK: ");
			errorReport.append(Build.VERSION.SDK);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Release: ");
			errorReport.append(Build.VERSION.RELEASE);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Incremental: ");
			errorReport.append(Build.VERSION.INCREMENTAL);
			errorReport.append(LINE_SEPARATOR);

			Intent intent = new Intent(context.getApplication(), CrashReportActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);  
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("error", errorReport.toString());
			context.getApplication().startActivity(intent);

			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(10);		
	}
}
